<template>
    <Layout>
      <div class="tag-container">
        <!-- 功能入口区域 -->
        <div class="function-area">
          <el-button type="primary" @click="handleCreateTag">新建标签</el-button>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入标签名称"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
  
        <!-- 数据列表 -->
        <div class="data-table">
          <el-table
            :data="tagList"
            style="width: 100%"
            v-loading="loading"
            border
          >
            <el-table-column prop="name" label="标签名称" width="200" />
            <el-table-column label="标签颜色" width="120">
              <template #default="scope">
                <div
                  class="color-block"
                  :style="{ backgroundColor: scope.row.color || '#409EFF' }"
                ></div>
                <span>{{ scope.row.color || '#409EFF' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="标签类型" width="120">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.type)">
                  {{ getTagTypeName(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
  
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
  
        <!-- 新建/编辑标签弹窗 -->
        <el-dialog
          v-model="dialogVisible"
          :title="isEdit ? '编辑标签' : '新增标签'"
          width="500px"
          center
        >
          <el-form
            ref="formRef"
            :model="tagForm"
            :rules="formRules"
            label-width="80px"
          >
            <el-form-item label="标签名称" prop="name">
              <el-input v-model="tagForm.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="标签类型" prop="type">
              <el-select v-model="tagForm.type" placeholder="请选择">
                <el-option :value="1" label="商品标签" />
                <el-option :value="2" label="促销标签" />
                <el-option :value="3" label="状态标签" />
              </el-select>
            </el-form-item>
            <el-form-item label="标签颜色" prop="color">
              <el-color-picker v-model="tagForm.color" show-alpha />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </Layout>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Search } from '@element-plus/icons-vue';
  import Layout from '@/components/Layout.vue';
  import { getTagList, createTag, updateTag, deleteTag } from '@/api/tag';
  
  // 加载状态
  const loading = ref(false);
  
  // 标签列表数据
  const tagList = ref<any[]>([]);
  
  // 分页相关
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  
  // 搜索关键字
  const searchKeyword = ref('');
  
  // 弹窗相关
  const dialogVisible = ref(false);
  const isEdit = ref(false);
  const formRef = ref();
  
  // 标签表单
  const tagForm = reactive({
    objectId: '',
    name: '',
    type: 1,
    color: '#409EFF'
  });
  
  // 表单校验规则
  const formRules = {
    name: [
      { required: true, message: '请输入标签名称', trigger: 'blur' },
      { max: 50, message: '标签名称不能超过50个字符', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择标签类型', trigger: 'change' }
    ]
  };
  
  // 获取标签类型名称
  const getTagTypeName = (type: number) => {
    switch (type) {
      case 1:
        return '商品标签';
      case 2:
        return '促销标签';
      case 3:
        return '状态标签';
      default:
        return '未知类型';
    }
  };
  
  // 获取标签类型样式
  const getTagType = (type: number) => {
    switch (type) {
      case 1:
        return '';
      case 2:
        return 'success';
      case 3:
        return 'warning';
      default:
        return 'info';
    }
  };
  
  // 加载标签列表
  const loadTagList = async () => {
    loading.value = true;
    try {
      const response = await getTagList();
      const data = response.data || {};
      tagList.value = data.results || [];
      total.value = data.count || 0;
    } catch (error) {
      console.error('获取标签列表失败:', error);
      ElMessage.error('获取标签列表失败');
    } finally {
      loading.value = false;
    }
  };
  
  // 处理搜索
  const handleSearch = () => {
    currentPage.value = 1;
    loadTagList();
  };
  
  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    loadTagList();
  };
  
  // 处理每页条数变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
    loadTagList();
  };
  
  // 处理新建标签
  const handleCreateTag = () => {
    isEdit.value = false;
    resetForm();
    dialogVisible.value = true;
  };
  
  // 处理编辑
  const handleEdit = (row: any) => {
    isEdit.value = true;
    resetForm();
    
    // 填充表单数据
    tagForm.objectId = row.objectId;
    tagForm.name = row.name;
    tagForm.type = row.type || 1;
    tagForm.color = row.color || '#409EFF';
    
    dialogVisible.value = true;
  };
  
  // 处理删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确定要删除该标签吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteTag(row.objectId);
        ElMessage.success('删除成功');
        loadTagList();
      } catch (error) {
        console.error('删除标签失败:', error);
        ElMessage.error('删除标签失败');
      }
    }).catch(() => {});
  };
  
  // 重置表单
  const resetForm = () => {
    tagForm.objectId = '';
    tagForm.name = '';
    tagForm.type = 1;
    tagForm.color = '#409EFF';
    if (formRef.value) {
      formRef.value.resetFields();
    }
  };
  
  // 处理提交
  const handleSubmit = async () => {
    if (!formRef.value) return;
    
    await formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const data = {
            name: tagForm.name,
            type: tagForm.type,
            color: tagForm.color
          };
          
          if (isEdit.value) {
            await updateTag(tagForm.objectId, data);
            ElMessage.success('编辑成功');
          } else {
            await createTag(data);
            ElMessage.success('新增成功');
          }
          
          dialogVisible.value = false;
          loadTagList();
        } catch (error) {
          console.error('保存标签失败:', error);
          ElMessage.error('保存标签失败');
        }
      }
    });
  };
  
  // 页面加载时获取数据
  onMounted(() => {
    loadTagList();
  });
  </script>
  
  <style scoped>
  .tag-container {
    padding: 0;
  }
  
  .function-area {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  
  .search-box {
    width: 300px;
  }
  
  .data-table {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .color-block {
    display: inline-block;
    width: 20px;
    height: 20px;
    margin-right: 8px;
    border-radius: 2px;
    vertical-align: middle;
  }
  </style>